/**
 * 
 */
package com.ydy.service.email.impl;

import java.io.File;
import java.util.Map.Entry;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.ydy.exception.BusinessException;
import com.ydy.ienum.EnumEmail;
import com.ydy.service.email.EmailService;
import com.ydy.utils.StringUtils;
import com.ydy.vo.email.EmailVo;

/**
 * @author xuzhaojie
 *
 *         2019年3月5日 上午10:33:02
 */
@Service
public class EmailServiceImpl implements EmailService {

	private final static Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);

	private static final ThreadLocal<Integer> THREAD_LOCAL = new ThreadLocal<Integer>();
	private static final Integer RETRY_TIME = 3;

	@Autowired
	private JavaMailSender javaMailSender;

	@Value("${mail_username}")
	private String from;

	// 定义正则表达式
	private static final String REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";

	@Override
	public void sendHtmlMail(EmailVo vo, boolean isShowHtml) {
		try {
			if (StringUtils.isEmpty(vo.getEmail())) {
				log.error("邮件收件人不可为空");
				throw new BusinessException(EnumEmail.REC_EMPTY);
			}
			if (!vo.getEmail().matches(REGEX)) {
				log.error("邮件地址格式不正确:" + vo.getEmail());
				throw new BusinessException(EnumEmail.EAMIL_FORMAT_NOT_FIT);
			}
			if (StringUtils.isEmpty(vo.getTitle())) {
				log.error("邮件标题不可为空");
				throw new BusinessException(EnumEmail.SUBJECT_EMPTY);
			}
			if (StringUtils.isEmpty(vo.getContent())) {
				log.error("邮件内容不可为空");
				throw new BusinessException(EnumEmail.CONTENT_EMPTY);
			}
			MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			// 是否发送的邮件是富文本（附件，图片，html等）
			MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
			messageHelper.setFrom(from);// 发送人的邮箱
			messageHelper.setTo(vo.getEmail());// 发给谁 对方邮箱
			messageHelper.setSubject(vo.getTitle());// 标题
			messageHelper.setText(vo.getContent(), isShowHtml);// false，显示原始html代码，无效果
			// 判断是否有附加图片等
			if (!CollectionUtils.isEmpty(vo.getAttachment())) {
				for (Entry<String, Object> entry : vo.getAttachment().entrySet()) {
					File file = new File(String.valueOf(entry.getValue()));
					if (file.exists()) {
						messageHelper.addAttachment(entry.getKey(), new FileSystemResource(file));
					}
				}
			}
			send(mimeMessage);
			log.info("邮件发送成功! From:" + from + ",To:" + vo.getEmail() + ",subject:" + vo.getTitle());
		} catch (Exception e) {
			throw new BusinessException(EnumEmail.SEND_EAMIL_ERROR);
		}
	}

	private void send(MimeMessage mimeMessage) {
		Integer time = THREAD_LOCAL.get();
		if (time == null) {
			time = RETRY_TIME.intValue();
			THREAD_LOCAL.set(time);
		}
		try {
			if (time < 0) {
				log.error("重复次数用完,发送邮件失败");
				throw new BusinessException(EnumEmail.SEND_EAMIL_ERROR);
			}
			time--;
			THREAD_LOCAL.set(time);
			javaMailSender.send(mimeMessage);
			THREAD_LOCAL.remove();
		} catch (MailException e) {
			log.error("发送邮件出现错误:{}", e.getMessage());
			if (time >= 0) {
				log.info("正在重新发送第 {} 次", RETRY_TIME - time);
			}
			send(mimeMessage);
		}
	}
}
